package com.tju.ocean_ecology_website.service.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.tju.ocean_ecology_website.entity.VolunteerInfo;
import com.tju.ocean_ecology_website.entity.VolunteerServiceRecord;
import com.tju.ocean_ecology_website.dao.VolunteerInfoDao;
import com.tju.ocean_ecology_website.dao.VolunteerServiceRecordDao;
import com.tju.ocean_ecology_website.service.VolunteerServiceRecordService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 志愿者服务记录表(VolunteerServiceRecord)表服务实现类
 *
 * @author shaolong
 * @since 2025-05-02 13:30:00
 */
@Service("volunteerServiceRecordService")
public class VolunteerServiceRecordServiceImpl implements VolunteerServiceRecordService {
    @Resource
    private VolunteerServiceRecordDao volunteerServiceRecordDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public VolunteerServiceRecord queryById(Long id) {
        return this.volunteerServiceRecordDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param volunteerServiceRecord 筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<VolunteerServiceRecord> queryByPage(VolunteerServiceRecord volunteerServiceRecord, PageRequest pageRequest) {
        long total = this.volunteerServiceRecordDao.count(volunteerServiceRecord);
        return new PageImpl<>(this.volunteerServiceRecordDao.queryAllByLimit(volunteerServiceRecord, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param volunteerServiceRecord 实例对象
     * @return 实例对象
     */
    @Override
    public VolunteerServiceRecord insert(VolunteerServiceRecord volunteerServiceRecord) {
        Date now = new Date();
        volunteerServiceRecord.setCreateTime(now);
        volunteerServiceRecord.setUpdateTime(now);
        this.volunteerServiceRecordDao.insert(volunteerServiceRecord);
        return volunteerServiceRecord;
    }

    /**
     * 修改数据
     *
     * @param volunteerServiceRecord 实例对象
     * @return 实例对象
     */
    @Override
    public VolunteerServiceRecord update(VolunteerServiceRecord volunteerServiceRecord) {
        volunteerServiceRecord.setUpdateTime(new Date());
        this.volunteerServiceRecordDao.update(volunteerServiceRecord);
        return this.queryById(volunteerServiceRecord.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.volunteerServiceRecordDao.deleteById(id) > 0;
    }

    /**
     * 根据志愿者ID查询服务记录
     *
     * @param volunteerId 志愿者ID
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<VolunteerServiceRecord> queryByVolunteerId(Long volunteerId, PageRequest pageRequest) {
        List<VolunteerServiceRecord> records = this.volunteerServiceRecordDao.queryByVolunteerId(volunteerId, pageRequest);
        long total = this.volunteerServiceRecordDao.countByVolunteerId(volunteerId);
        return new PageImpl<>(records, pageRequest, total);
    }

    @Resource
    private VolunteerInfoDao volunteerInfoDao;

    /**
     * 审核通过服务时长记录
     *
     * @param id 记录ID
     * @return 实例对象
     */
    @Override
    public VolunteerServiceRecord approveServiceHour(Long id) {
        VolunteerServiceRecord record = this.queryById(id);
        if (record != null) {
            // 如果记录已经是已通过状态，直接返回
            if (record.getStatus() != null && record.getStatus() == 1) {
                return record;
            }

            // 更新记录状态
            record.setStatus(1); // 已通过
            record.setUpdateTime(new Date());
            this.volunteerServiceRecordDao.update(record);

            // 更新志愿者的总服务时长
            updateVolunteerTotalHours(record.getVolunteerId());

            return this.queryById(id);
        }
        return null;
    }

    /**
     * 拒绝服务时长记录
     *
     * @param id 记录ID
     * @param reason 拒绝原因
     * @return 实例对象
     */
    @Override
    public VolunteerServiceRecord rejectServiceHour(Long id, String reason) {
        VolunteerServiceRecord record = this.queryById(id);
        if (record != null) {
            // 如果记录已经是已拒绝状态，直接返回
            if (record.getStatus() != null && record.getStatus() == 2) {
                return record;
            }

            // 如果记录当前是已通过状态，需要重新计算志愿者的总服务时长
            boolean needUpdateTotalHours = record.getStatus() != null && record.getStatus() == 1;

            record.setStatus(2); // 已拒绝
            // 注意：当前实体类中没有拒绝原因字段，可以将拒绝原因存入description字段
            String currentDesc = record.getDescription() != null ? record.getDescription() : "";
            record.setDescription(currentDesc + "\n拒绝原因：" + reason);
            record.setUpdateTime(new Date());
            this.volunteerServiceRecordDao.update(record);

            // 如果之前是已通过状态，需要重新计算志愿者的总服务时长
            if (needUpdateTotalHours) {
                updateVolunteerTotalHours(record.getVolunteerId());
            }

            return this.queryById(id);
        }
        return null;
    }

    /**
     * 导出服务时长记录
     *
     * @param volunteerServiceRecord 筛选条件
     * @return 服务时长记录列表
     */
    @Override
    public List<VolunteerServiceRecord> exportServiceHours(VolunteerServiceRecord volunteerServiceRecord) {
        return this.volunteerServiceRecordDao.exportServiceHours(volunteerServiceRecord);
    }

    /**
     * 查询所有符合条件的数据（不分页）
     *
     * @param volunteerServiceRecord 查询条件
     * @return 对象列表
     */
    @Override
    public List<VolunteerServiceRecord> queryAll(VolunteerServiceRecord volunteerServiceRecord) {
        // 使用大的分页参数来获取所有数据
        return this.volunteerServiceRecordDao.queryAllByLimit(volunteerServiceRecord, PageRequest.of(0, Integer.MAX_VALUE));
    }

    /**
     * 定期统计所有志愿者的服务时长
     * 每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void scheduledUpdateAllVolunteerTotalHours() {
        // 查询所有志愿者
        List<VolunteerInfo> allVolunteers = volunteerInfoDao.queryAllByLimit(new VolunteerInfo(), PageRequest.of(0, Integer.MAX_VALUE));

        // 遍历每个志愿者，更新其总服务时长
        for (VolunteerInfo volunteer : allVolunteers) {
            updateVolunteerTotalHours(volunteer.getId());
        }
    }

    /**
     * 更新志愿者的总服务时长
     *
     * @param volunteerId 志愿者ID
     */
    @Override
    public void updateVolunteerTotalHours(Long volunteerId) {
        if (volunteerId == null) {
            return;
        }

        // 查询志愿者信息
        VolunteerInfo volunteerInfo = volunteerInfoDao.queryById(volunteerId);
        if (volunteerInfo == null) {
            // 如果没有找到志愿者信息，尝试通过用户ID查询
            VolunteerInfo query = new VolunteerInfo();
            query.setUserId(volunteerId);
            List<VolunteerInfo> volunteerInfos = volunteerInfoDao.queryAllByLimit(query, PageRequest.of(0, 1));
            if (!volunteerInfos.isEmpty()) {
                volunteerInfo = volunteerInfos.get(0);
            } else {
                return; // 如果仍然找不到，直接返回
            }
        }

        // 查询已审核通过的服务记录
        VolunteerServiceRecord query = new VolunteerServiceRecord();
        query.setVolunteerId(volunteerId);
        query.setStatus(1); // 已通过
        List<VolunteerServiceRecord> records = this.queryAll(query);

        // 统计总服务时长
        int totalHours = 0;
        for (VolunteerServiceRecord record : records) {
            if (record.getServiceHours() != null) {
                totalHours += record.getServiceHours();
            }
        }

        // 更新志愿者的总服务时长
        volunteerInfo.setVolunteerHours(totalHours);
        volunteerInfo.setUpdateTime(new Date());
        volunteerInfoDao.update(volunteerInfo);
    }

    /**
     * 获取志愿者本月服务时长
     *
     * @param volunteerId 志愿者ID
     * @return 本月服务时长
     */
    @Override
    public double getMonthServiceHours(Long volunteerId) {
        if (volunteerId == null) {
            return 0;
        }

        // 获取当前月份的开始和结束日期
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为当月第一天
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date monthStart = calendar.getTime();

        calendar.add(Calendar.MONTH, 1); // 下个月
        Date nextMonth = calendar.getTime();

        // 查询本月已审核通过的服务记录
        List<VolunteerServiceRecord> records = this.volunteerServiceRecordDao.queryByVolunteerIdAndDateRange(
                volunteerId, monthStart, nextMonth, 1);

        // 累加服务时长
        double totalHours = 0;
        for (VolunteerServiceRecord record : records) {
            if (record.getServiceHours() != null) {
                totalHours += record.getServiceHours();
            }
        }

        return totalHours;
    }

    /**
     * 获取志愿者排名
     *
     * @param volunteerId 志愿者ID
     * @return 排名情况（例如：前10%）
     */
    @Override
    public String getVolunteerRank(Long volunteerId) {
        if (volunteerId == null) {
            return "暂无排名";
        }

        // 查询志愿者信息
        VolunteerInfo volunteerInfo = volunteerInfoDao.queryById(volunteerId);
        if (volunteerInfo == null) {
            // 如果没有找到志愿者信息，尝试通过用户ID查询
            VolunteerInfo query = new VolunteerInfo();
            query.setUserId(volunteerId);
            List<VolunteerInfo> volunteerInfos = volunteerInfoDao.queryAllByLimit(query, PageRequest.of(0, 1));
            if (!volunteerInfos.isEmpty()) {
                volunteerInfo = volunteerInfos.get(0);
            } else {
                return "暂无排名"; // 如果仍然找不到，直接返回
            }
        }

        // 获取当前志愿者的服务时长
        Integer currentHours = volunteerInfo.getVolunteerHours();
        if (currentHours == null || currentHours == 0) {
            return "暂无排名";
        }

        // 查询所有志愿者的服务时长并排序
        List<VolunteerInfo> allVolunteers = volunteerInfoDao.queryAllByLimit(new VolunteerInfo(), PageRequest.of(0, Integer.MAX_VALUE));

        // 过滤掉没有服务时长的志愿者
        List<VolunteerInfo> validVolunteers = allVolunteers.stream()
                .filter(v -> v.getVolunteerHours() != null && v.getVolunteerHours() > 0)
                .sorted((v1, v2) -> v2.getVolunteerHours().compareTo(v1.getVolunteerHours()))
                .collect(Collectors.toList());

        if (validVolunteers.isEmpty()) {
            return "暂无排名";
        }

        // 找到当前志愿者的排名
        int rank = 0;
        for (int i = 0; i < validVolunteers.size(); i++) {
            if (validVolunteers.get(i).getId().equals(volunteerInfo.getId()) ||
                    validVolunteers.get(i).getUserId().equals(volunteerInfo.getUserId())) {
                rank = i + 1;
                break;
            }
        }

        if (rank == 0) {
            return "暂无排名";
        }

        // 计算百分比
        int percentage = (int) Math.ceil((double) rank / validVolunteers.size() * 100);

        // 如果在前10%，返回前10%
        if (percentage <= 10) {
            return "前10%";
        } else if (percentage <= 30) {
            return "前30%";
        } else if (percentage <= 50) {
            return "前50%";
        } else {
            return "前" + percentage + "%";
        }
    }

    /**
     * 获取志愿者等级
     *
     * @param totalHours 总服务时长
     * @return 志愿者等级信息（当前等级、下一等级、下一等级所需时长、距离下一等级还需时长）
     */
    @Override
    public Map<String, Object> getVolunteerLevel(double totalHours) {
        Map<String, Object> result = new HashMap<>();

        // 定义志愿者等级和所需时长
        String[] levels = {"新手志愿者", "初级志愿者", "中级志愿者", "高级志愿者", "资深志愿者", "金牌志愿者"};
        int[] hourRequirements = {0, 50, 100, 200, 500, 1000};

        // 确定当前等级
        String currentLevel = levels[0];
        String nextLevel = levels[1];
        int nextLevelHours = hourRequirements[1];
        double hoursToNextLevel = nextLevelHours - totalHours;

        for (int i = 1; i < levels.length; i++) {
            if (totalHours >= hourRequirements[i]) {
                currentLevel = levels[i];
                if (i < levels.length - 1) {
                    nextLevel = levels[i + 1];
                    nextLevelHours = hourRequirements[i + 1];
                    hoursToNextLevel = nextLevelHours - totalHours;
                } else {
                    // 已经是最高等级
                    nextLevel = currentLevel;
                    nextLevelHours = hourRequirements[i];
                    hoursToNextLevel = 0;
                }
            } else {
                nextLevel = levels[i];
                nextLevelHours = hourRequirements[i];
                hoursToNextLevel = nextLevelHours - totalHours;
                break;
            }
        }

        result.put("level", currentLevel);
        result.put("nextLevel", nextLevel);
        result.put("nextLevelHours", nextLevelHours);
        result.put("hoursToNextLevel", hoursToNextLevel);

        return result;
    }

    /**
     * 根据志愿者ID和日期范围查询服务记录
     *
     * @param volunteerId 志愿者ID
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param status 状态（0-待审核, 1-已通过, 2-已拒绝）
     * @return 服务记录列表
     */
    @Override
    public List<VolunteerServiceRecord> queryByVolunteerIdAndDateRange(Long volunteerId, Date startDate, Date endDate, Integer status) {
        return this.volunteerServiceRecordDao.queryByVolunteerIdAndDateRange(volunteerId, startDate, endDate, status);
    }
}
